﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BaseText;
using Srvtools;

public partial class WorkTimeN_WorkTimeLeave : System.Web.UI.Page
{
    private Srvtools.WebDataSet WMaster;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request["sid"] != null)
            {
                InitializeComponent(true);

                FLWebNavigator1.Visible = true;
                Master.DataSource = WMaster;
                WMaster.SetWhere("LeaveId=" + Request["sid"].ToString());

                string FlowFlag = Request["FlowFlag"].ToString();
                string EmployeeId = Request["EmployeeId"].ToString();
                if (FlowFlag == "" && Convert.ToInt32("0" + EmployeeId) == Convert.ToInt32(Srvtools.CliUtils.fLoginUser))
                {
                }
                else
                {
                    object o = FLWebNavigator1.NavControls["Comment"];
                    FLWebNavigator1.NavControls.Clear();
                    FLWebNavigator1.NavControls.Add(o);
                }

                DataSet ds = WMaster.Execute("SELECT SYS_TODOLIST.LISTID FROM SYS_TODOLIST WHERE  SYS_TODOLIST.FORM_TABLE='WorkTime_Leave'" +
                    " and SYS_TODOLIST.FORM_KEYS='LeaveId' and  SYS_TODOLIST.FORM_PRESENTATION='LeaveId=" + Request["sid"].ToString() + "'");
                if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    ImageButton imb = new ImageButton();
                    imb.ImageUrl = "../image/uipics/Comment_C.gif";
                    imb.ID = "i";
                    imb.Attributes.Add("onclick", "window.open('../InnerPages/FlowComment.aspx?LISTID=" + ds.Tables[0].Rows[0][0].ToString()
                        + "&ATTACHMENTS=', '', 'resizable=yes,scrollbars=yes,width=645,height=400,top=100,left=200');return false");
                    FLWebNavigator1.Controls.Add(imb);
                   
                }


            }
            else
            {
                InitializeComponent(false);
                Master.DataSource = WMaster;

                WorkTime_YearHoliday_Days1.EmployeeId = GetEmployeeId();
                WorkTime_YearHoliday_Days1.ReLoad();
                ToneOffList1.EmployeeId = GetEmployeeId();
                ToneOffList1.ReLoad();
            }

            MasterPage_MasterPage mpg = (MasterPage_MasterPage)this.Page.Master;
            mpg.HelpHref = "~/Help/WorkTime/请假申请流程.htm";
            mpg.PageName = "员工请假单";
            mpg.PicUrl = "";
            mpg.IntiBar();
        }

    }

    #region 系统
    private void InitializeComponent(bool action)
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WorkTimeN_WorkTimeLeave));
        this.WMaster = new Srvtools.WebDataSet();
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).BeginInit();
        // 
        // WMaster
        // 
        this.WMaster.Active = false;
        this.WMaster.AlwaysClose = true;
        this.WMaster.DeleteIncomplete = true;
        this.WMaster.Guid = null;
        this.WMaster.LastKeyValues = null;
        this.WMaster.Locale = new System.Globalization.CultureInfo("zh-CN");
        this.WMaster.PacketRecords = 100;
        this.WMaster.Position = -1;
        this.WMaster.RemoteName = "SWorkTime.WorkTime_Leave";
        this.WMaster.ServerModify = true;
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).EndInit();

    }

    #endregion

    #region 事件

    protected void WebFormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
    {

        try
        {
            //TextBox startDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox3");
            //TextBox endDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox4");

            //if (startDate == null || endDate == null)
            //    return;

            //int hours = this.GetHours(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(endDate.Text));
            e.Values["LeaHours"] = 0;
        }
        catch (Exception ex)
        {

        }
    }

    protected void WebFormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        //TextBox startDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox1");
        //TextBox endDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox2");

        //if (startDate == null || endDate == null)
        //    return;

        //int hours = this.GetHours(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(endDate.Text));
        e.NewValues["LeaHours"] = 0;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ZLTextBox tbHours = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox5");
        ZLTextBox startDate = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox1");
        ZLTextBox endDate = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox2");
        if (tbHours == null || startDate == null || endDate == null)
            return;
        if (this.ValidateDate(startDate.GetDateTime, endDate.GetDateTime) == false)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('终止日期必须大于起始日期\\r\\n或是\\r\\n请假时间不在工作时间之内');", true);
            return;
        }
        tbHours.Text = this.GetHours(startDate.GetDateTime, endDate.GetDateTime).ToString();

    }

    #endregion

    #region 验证

    private DateTime start = DateTime.MinValue;
    private DateTime end = DateTime.MinValue;

    protected bool ValidateDateFrom(object value)
    {
        TextBox ZLTextBox1 = (TextBox)this.WebFormView1.FindControl("ZLTextBox3");
        TextBox ZLTextBox2 = (TextBox)this.WebFormView1.FindControl("ZLTextBox4");
        DateTime st = DateTime.Parse(ZLTextBox1.Text);
        DateTime et = DateTime.Parse(ZLTextBox2.Text);
        if (st.CompareTo(et) <= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    protected bool ValidateDateTo(object value)
    {
        return true;
        end = DateTime.Parse(value.ToString());
        ZLTextBox ZLTextBox1 = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox1");
        ZLTextBox ZLTextBox2 = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox2");
        DateTime st = DateTime.Parse(ZLTextBox1.textValue);
        DateTime et = DateTime.Parse(ZLTextBox1.textValue);
        if (st.CompareTo(et) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private bool ValidateDate(DateTime start, DateTime end)
    {
        if (start != DateTime.MinValue && end != DateTime.MinValue)
        {
            int sHour = start.Hour;
            int sMinute = start.Minute;
            int eHour = end.Hour;
            int eMinute = end.Minute;

            if (sHour < 8 || sHour == 8 && sMinute < 30 || sHour > 17 || eHour < 8 || eHour == 8 && eMinute < 30 || eHour > 17)
            {
                return false;
            }

            if (start.CompareTo(end) >= 0)
            {
                return false;
            }
        }
        return true;
    }

    #endregion

    #region 自定义方法

    private int GetHours(DateTime start, DateTime end)
    {
        return 0;

        int counHour = 0;
        Hashtable CompWorkDateDefine;

        object[] objParam = new object[2];
        objParam[0] = start.Year.ToString().Trim() + "-" + start.Month.ToString().Trim() + "-" + start.Day.ToString().Trim();
        objParam[1] = end.Year.ToString().Trim() + "-" + end.Month.ToString().Trim() + "-" + end.Day.ToString().Trim();
        object[] myRet = CliUtils.CallMethod("SWorkTime", "GetCompWorkDateDefine", objParam);
        if (myRet != null && (int)myRet[0] == 0)
        {
            CompWorkDateDefine = (Hashtable)myRet[1];
        }
        else
        {
            CompWorkDateDefine = new Hashtable();
        }

        DateTime stDate = start;

        int sHour = start.Hour;
        int eHour = end.Hour;

        if (stDate.Year == end.Year && stDate.Month == end.Month && stDate.Day == end.Day)
        {
            if ((sHour >= 12) || (eHour <= 12))
            {
                counHour = 4;
            }

            else
            {
                counHour = 8;
            }

        }
        else
        {
            while (stDate <= end)
            {
                string Dkey = stDate.Year.ToString().Trim() + "-" + stDate.Month.ToString().Trim() + "-" + stDate.Day.ToString().Trim();
                if (CompWorkDateDefine.ContainsKey(Dkey) == false)
                {
                    if (stDate.DayOfWeek != DayOfWeek.Saturday && stDate.DayOfWeek != DayOfWeek.Sunday)
                    {
                        counHour += 8;
                        if (stDate.Year == start.Year && stDate.Month == start.Month && stDate.Day == start.Day)
                        {
                            if (sHour >= 12) counHour -= 4;
                        }
                        if (stDate.Year == end.Year && stDate.Month == end.Month && stDate.Day == end.Day)
                        {
                            if (eHour <= 12) counHour -= 4;
                        }
                    }
                }
                else
                {
                    object[] DtIn = (object[])CompWorkDateDefine[Dkey];// { DTyp, DatePrepty };
                    bool Dbk = (bool)DtIn[0];
                    if (Dbk == true)
                    {
                        counHour += 8;
                        if (stDate.Year == start.Year && stDate.Month == start.Month && stDate.Day == start.Day)
                        {
                            if (sHour >= 12) counHour -= 4;
                        }
                        if (stDate.Year == end.Year && stDate.Month == end.Month && stDate.Day == end.Day)
                        {
                            if (eHour <= 12) counHour -= 4;
                        }
                    }
                }

                stDate = stDate.AddDays(1);
            }

        }

        return counHour;

    }


    protected bool IsDepVisible(string dep)
    {
        return dep != string.Empty;
    }

    protected bool Disp()
    {
        if (Request.Params["A"] != null)
            return true;
        else
            return false;
    }

    #endregion

    #region 默认值绑定

    protected object GetDateTo()
    {
        //return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[0].ToString()).AddHours(-1)).ToString() : "");
        return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[1].ToString())).ToString() : "");
    }

    protected object GetDateFrom()
    {
       // return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[1].ToString()).AddHours(1)).ToString() : "");
         return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[0].ToString())).ToString() : "");
    }

    protected string GetEmployeeId()
    {
        String str = Srvtools.CliUtils.GetValue("_UserCode")[1].ToString();
        str = int.Parse(str).ToString();
        return str;
    }

    #endregion


    protected void Button1_Click1(object sender, EventArgs e)
    {
        TextBox tbNumber = (TextBox)this.WebFormView1.FindControl("LeaveIdTextBox");
        string strNum = tbNumber.Text;

        TextBox tbEmployeeId = (TextBox)this.WebFormView1.FindControl("tbEmployeeId");
        string strEid = tbEmployeeId.Text;

        WebRefVal tbEmployeeIdT = (WebRefVal)this.WebFormView1.FindControl("tbEmployeeId2");
        string strEid2 = tbEmployeeIdT.BindingValue;

        ZLTextBox tbStartDate = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox1");
        int year = tbStartDate.GetDateTime.Year;

        TextBox tbHours = (TextBox)this.WebFormView1.FindControl("LeaHoursTextBox");
        float days = 0;
        float mol = 0;
        int h = int.Parse(tbHours.Text);
        if (h == 4)
        {
            days += 0.5f;
        }
        else
        {
            days = (h / 4);
            days = int.Parse(days.ToString()) / 2;
            mol = h % 4;
            if (mol > 0) days += 0.5f;
        }
        days = -days;

        if (days < -0.3)
        {
            //先查是否已存数据，是进行删除
            string selectSql = string.Format("select * from WorkTime_YearHoliday where sheetId={0}", strNum);
            DataSet ds = CliUtils.ExecuteSql("GLModule", "cmdRefValUse", selectSql, true, CliUtils.fCurrentProject);
            if (ds.Tables[0].Rows.Count > 0)
            {
                string deleteSql = string.Format(" DELETE FROM [WorkTime_YearHoliday] WHERE SheetId={0}", strNum);
                CliUtils.ExecuteSql("GLModule", "cmdRefValUse", deleteSql, true, CliUtils.fCurrentProject);
            }

            string DYear = "";
            Single SDays = 0;

            object[] objParam = new object[2];
            objParam[0] = strEid;
            objParam[1] = strNum;

            object[] myRet = CliUtils.CallMethod("SWorkTime", "GetSumDaysOfYearHolidayGroupByLYear", objParam);
            if (myRet != null && (int)myRet[0] == 0)
            {
                DYear = (string)myRet[1];
                SDays = (Single)myRet[2];
                if (DYear.Length == 0) DYear = DateTime.Now.Year.ToString();
            }

            if ((SDays + days) > (-0.3)) //请假天数小于当前最早的年度的可用数据
            {

                string insertSql = "insert into WorkTime_YearHoliday (EmployeeId,Years,Days,DataType,SheetId) values ({0},{1},{2},{3},{4})";
                insertSql = string.Format(insertSql, strEid, DYear, days, 21, strNum);

                CliUtils.ExecuteSql("GLModule", "cmdRefValUse", insertSql, true, CliUtils.fCurrentProject);
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('请假数据已传输至带薪假数据表！')", true);
            }
            else //请假天数大于当前最早的年度的可用数据，多余的数据传到下一年度
            {

                // 写入最早的年度的数据
                string insertSql = "insert into WorkTime_YearHoliday (EmployeeId,Years,Days,DataType,SheetId) values ({0},{1},{2},{3},{4})";
                insertSql = string.Format(insertSql, strEid, DYear, (SDays * -1), 21, strNum);
                CliUtils.ExecuteSql("GLModule", "cmdRefValUse", insertSql, true, CliUtils.fCurrentProject);
                // 写入下一年度的数据
                string NDYear = Convert.ToString(int.Parse(DYear) + 1);
                insertSql = "insert into WorkTime_YearHoliday (EmployeeId,Years,Days,DataType,SheetId) values ({0},{1},{2},{3},{4})";
                insertSql = string.Format(insertSql, strEid, NDYear, (SDays + days), 21, strNum);
                CliUtils.ExecuteSql("GLModule", "cmdRefValUse", insertSql, true, CliUtils.fCurrentProject);
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('请假数据已传输至带薪假数据表！')", true);
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('0天请假天数无法传输！')", true);
        }

    }

    object[] oDiff = null;
    protected void WebFormView1_DataBound(object sender, EventArgs e)
    {
        if (WebFormView1.CurrentMode == FormViewMode.ReadOnly)
        {
            TextBox tbEmployeeId = (TextBox)this.WebFormView1.FindControl("tbEmployeeId");
            if (tbEmployeeId.Text != "")
            {
                WorkTime_YearHoliday_Days1.EmployeeId = tbEmployeeId.Text;
                ToneOffList1.EmployeeId = tbEmployeeId.Text;
                ToneOffList1.ReLoad();
                WorkTime_YearHoliday_Days1.ReLoad();
            }

            WebDropDownList ddl = (WebDropDownList)this.WebFormView1.FindControl("WebDropDownList2");
            Button tbButton = (Button)this.WebFormView1.FindControl("Button1");
            if (ddl.SelectedValue == "1")
                tbButton.Enabled = true;
            else
                tbButton.Enabled = false;
        }
        else if (WebFormView1.CurrentMode == FormViewMode.Insert || WebFormView1.CurrentMode == FormViewMode.Edit)
        {
            if (Request.Params["MS"] != null)
            {
                WebRefVal tbEmployee = (WebRefVal)this.WebFormView1.FindControl("WebRefVal1");
                if (tbEmployee != null)
                    tbEmployee.ReadOnly = false;
            }
            else
            {
                WebRefVal tbEmployee = (WebRefVal)this.WebFormView1.FindControl("WebRefVal1");
                if (tbEmployee != null)
                    tbEmployee.ReadOnly = true;
            }
        }

    }

    protected void FLWebNavigator1_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "cmdAdd")
        {
            object[] myRet = CliUtils.CallMethod("SWorkTime", "GetWorkOnType", new object[1] { "WorkTime_WorkOnTypeGroup.EmployeeId=" + Convert.ToInt32(Srvtools.CliUtils.GetValue("_UserCode")[1].ToString()) });
            switch (myRet[1].ToString())
            {
                case "N":
                case "S":
                    oDiff = new object[] { ((DataSet)myRet[2]).Tables[0].Rows[0]["ect"].ToString(), ((DataSet)myRet[2]).Tables[0].Rows[0]["st"].ToString() };
                    break;
                default:
                    oDiff = new object[] { "08:30", "17:30" };
                    break;
            }
        }
        else if (e.CommandName == "cmdApply")
        {
            if (IsPostBack==true )
            {
                if (Request["sid"] != null)
                {
                    //Master.Reload();
                    Master.SetWhere("LeaveId=" + Request["sid"].ToString());
                }
                else
                {
                   // Master.Reload();
                }
            }
            
        }
    }

    protected void Master_ApplyError(object sender, ApplyErrorEventArgs e)
    {
        //Response.Write(e.Exception.Message);

        string msg = e.Exception.Message.Replace("\n", "\\n");
        e.Cancel = true;
        ClientScript.RegisterStartupScript(GetType(), "", "alert('" + msg + "');location.href='WorkTimeLeave.aspx?FLOWFILENAME=" +
            Server.UrlEncode(Server.UrlDecode(Request["FLOWFILENAME"])) + "&NAVMODE=Insert&FLNAVMODE=Submit'", true);

    }
}
